package cn.wolfcode.mp.web.controller;


import cn.wolfcode.mp.anno.RequiredPermission;
import cn.wolfcode.mp.domain.Role;
import cn.wolfcode.mp.query.RoleQuery;
import cn.wolfcode.mp.service.IPermissionService;
import cn.wolfcode.mp.service.IRoleService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("role")
public class RoleController {

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;

    // 处理查询所有角色请求
    // /role/list 目前不带参数,响应HTML 格式内容
    @RequiredPermission(name="角色页面",expression="role:list")
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") RoleQuery qo) {
        //获取所有 部门数据,存到Model 中
        IPage<Role> page = roleService.queryPage(qo);
        model.addAttribute("page", page);
        return "role/list";
    }

    // 访问路径 /role/delete?id=id值
    // 处理查询所有角色删除的请求,浏览器重新发送一条请求去查询一次
    @RequiredPermission(name="角色删除",expression="role:delete")
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(Long id) {
        if (id != null) {
            roleService.removeById(id);
        }
        return "redirect:/role/list"; //让浏览器再发一条请求去查询
        //return JsonResult.success();
    }

    @RequiredPermission(name="角色新增/编辑",expression="role:saveOrUpdate")
    @RequestMapping("/input")
    public String input(Long id, Model model) {
        // 共享角色
        model.addAttribute("roles",roleService.list());
        //共享权限
        model.addAttribute("permissions",permissionService.list());

        if (id != null) {
            model.addAttribute("role", roleService.getById(id));
        }
        return "role/input";
    }

    // 处理保存的请求 /role/saveOrUpdate 带上参数
    @RequiredPermission(name="角色新增/编辑",expression="role:saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public String saveOrUpdate(Role role) {
        if (role.getId() != null) {
            roleService.saveOrUpdate(role);
        }
        return "redirect:/role/list"; //重定向
        //return JsonResult.success();
    }
}
